package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //如果购物车为空就不能下单
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        if(null==shoppingCarts&&shoppingCarts.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        }
        //如果地址为空也不能下单
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //构造数据插入数据到订单表

        Orders order =new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        orderMapper.inster(order);

        // 插入订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>(shoppingCarts.size());
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail =new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(order.getId());

            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        //下单后删除购物车的数据
        shoppingCartMapper.cleanAll(BaseContext.getCurrentId());

        //返回VO对象
        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO)throws Exception {
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口 生成预支付交易订单
        JSONObject jsonObject = weChatPayUtil.pay(ordersPaymentDTO.getOrderNumber(),//商户订单号
                new BigDecimal(0.01),//支付金额单位元
                "苍穹外卖订单",//商品描述
                user.getOpenid()//微信用户的openid
        );

        if(jsonObject.getString("code")!=null && jsonObject.getString("code").equals("ORDERPAID")){

            throw new OrderBusinessException("该订单已支付");

        }
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);

        vo.setPackageStr(jsonObject.getString("package"));
        return vo;


    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> page= orderMapper.pageQuery(ordersPageQueryDTO);


        ArrayList<OrderVO> list = new ArrayList<>();
        for (Orders order : page) {
            List<OrderDetail> orderDetail= orderDetailMapper.getByOrderId(order.getId());

            OrderVO orderVO =new OrderVO();
            BeanUtils.copyProperties(order,orderVO);

            orderVO.setOrderDetailList(orderDetail);

            list.add(orderVO);
        }


        return new PageResult(page.getTotal(),list);
    }


    /**
     * 支付成功 修改订单状态
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单号查询当前用户的订单
        Orders ordersDB =  orderMapper.getByNumberAndUserId(outTradeNo,userId);

        //根据订单id更新订单状态，支付方式，支付状态，结账时间
        Orders orders = Orders.builder().id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now()).build();

        orderMapper.update(orders);
//////////////////////////////////////////////



    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO=new OrderVO();
        if(null!=orders){
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetailList);

        }
        return orderVO;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {

        Orders orders = orderMapper.getById(id);
        if(orders!=null){
            List<OrderDetail> details = orderDetailMapper.getByOrderId(orders.getId());
            if(null!=details &&details.size()>0){

                for (OrderDetail detail : details) {
                    ShoppingCart shoppingCart=new ShoppingCart();
                    BeanUtils.copyProperties(detail,shoppingCart);
                    shoppingCart.setCreateTime(LocalDateTime.now());
                    shoppingCart.setUserId(BaseContext.getCurrentId());
                    shoppingCartMapper.insert(shoppingCart);
                }


            }

        }


    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Orders ord = orderMapper.getById(id);
        // 校验订单是否存在
        if (ord == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if(ord.getStatus()>2){
           throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        if(ord.getStatus()>Orders.TO_BE_CONFIRMED &&ord.getStatus()<Orders.CANCELLED){
            //退款
            /**
             * 支付状态 0未支付 1已支付 2退款
             */
            ord.setPayStatus(Orders.REFUND);
        }
        Orders orders =Orders.builder().id(id).status(Orders.CANCELLED).cancelReason("用户取消订单").cancelTime(LocalDateTime.now()).build();
        orderMapper.update(orders);

    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {


            Integer toBeConfirmed  = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
            Integer confirmed  = orderMapper.countStatus(Orders.CONFIRMED);
            Integer deliveryInProgress= orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

            OrderStatisticsVO statisticsVO =new OrderStatisticsVO();
            statisticsVO.setConfirmed(confirmed);
            statisticsVO.setDeliveryInProgress(deliveryInProgress);
            statisticsVO.setToBeConfirmed(toBeConfirmed);
        return statisticsVO;
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> ordersList = page.getResult();

        List<OrderVO> orderVOList = new ArrayList<>();



        if(null!=ordersList &&ordersList.size()>0){
            for (Orders orders : ordersList) {
                OrderVO orderVO=new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);

                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId());
                List<String> collect = orderDetails.stream().map(orderDetail -> {
                    String s = orderDetail.getName() + "*" + orderDetail.getNumber();
                    return s;
                }).collect(Collectors.toList());
                orderVO.setOrderDishes(collect.toString());
                orderVOList.add(orderVO);

            }



        }

        return new PageResult(page.getTotal(),orderVOList);
    }

    /**
     * 拒单操作
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders ord = orderMapper.getById(ordersRejectionDTO.getId());

        if(ord.getStatus()!=2){
            throw new OrderBusinessException("当前商品不是代接单状态不能拒单");
        }

        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO,orders);
        orders.setStatus(Orders.CANCELLED);

        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * \
     * 接单
     *
     * @param confirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO confirmDTO) {

        Orders orders = Orders.builder()
                .id(confirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        orderMapper.update(orders);

    }

    /**
     * 商家取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        }
        Orders ord =new Orders();
        BeanUtils.copyProperties(ordersCancelDTO,ord);
        ord.setCancelTime(LocalDateTime.now());
        ord.setStatus(Orders.CANCELLED);

        orderMapper.update(ord);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {

        Orders order= orderMapper.getById(id);
        if(!order.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders=Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders ord = orderMapper.getById(id);
        if(ord==null || !ord.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder().id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now()).build();

        orderMapper.update(orders);
    }

    /**
     * 根据number查询订单
     *
     * @param outTradeNo
     * @return
     */
    @Override
    public Orders getByNumber(String outTradeNo) {
        return orderMapper.getByNumber(outTradeNo);
    }

    /**
     * 用户催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
//基于WebSocket实现催单
        Map map =new HashMap();

        map.put("type",2);//2代表用户催单
        map.put("orderId",id);
        map.put("content","订单号："+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }


}
